package zy.blue7.im.core.codec;


/**
 * @Author: blue7
 * @Date: 2022/2/27 19:24
 * @Version 1.0
 * @Description
 */

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import zy.blue7.im.common.message.Header;
import zy.blue7.im.common.message.Message;
import zy.blue7.im.common.message.MessageInfo;
import zy.blue7.im.core.utils.SerializableUtils;

import java.util.List;

/**
 * 将一种消息 体 转换成另外一种消息体
 */
public class MessageCodec extends MessageToMessageCodec<MessageInfo, Message> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, List<Object> list) throws Exception {

        int contentLength = SerializableUtils.serializable(message).length;
        Header header = Header.builder()
                .version(1)
                .contentLength(contentLength)
                .sessionId("0001")
                .build();
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setHeader(header);
        messageInfo.setMessage(message);
        list.add(messageInfo);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, MessageInfo messageInfo, List<Object> list) throws Exception {
        list.add(messageInfo.getMessage());
    }
}
